package com.app.repository.impl;

import com.app.common.PageBean;
import com.app.common.enums.DataStatusEnum;
import com.app.bean.dto.RecommendQueryPage;
import com.app.entity.Recommend;
import com.app.repository.IRecommendRepository;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @autor xiaoyu.fang
 * @date 2019/10/10 11:18
 */
@Component
public class IRecommendRepositoryImpl implements IRecommendRepository<Recommend, ObjectId> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void updateDataStatusById(Integer dataStatus, ObjectId id) {
        Query query = new Query(Criteria.where("id").is(id));
        Update update = new Update();
        update.set("dataStatus", dataStatus);
        mongoTemplate.updateFirst(query, update, Recommend.class);
    }

    @Override
    public List<Recommend> queryRecommendation() {
        Query query = new Query(Criteria.where("dataStatus").is(DataStatusEnum.VALID.KEY));
        return mongoTemplate.find(query, Recommend.class);
    }

    @Override
    public PageBean queryPage(RecommendQueryPage page) {
        Sort sort = new Sort(Sort.Direction.DESC, "createAt");
        Pageable pageable = PageRequest.of(page.getPageNum(), page.getPageSize(), sort);
        Query query = new Query();
        Criteria criteria = new Criteria();
        if (!StringUtils.isEmpty(page.getTitle())) {
            Pattern pattern = Pattern.compile("^.*" + page.getTitle() + ".*$", Pattern.CASE_INSENSITIVE);
            criteria.and("title").regex(pattern);
        }
        if (!StringUtils.isEmpty(page.getDataStatus())) {
            criteria.and("dataStatus").is(page.getDataStatus());
        }
        query.addCriteria(criteria).with(pageable);
        List<Recommend> list = mongoTemplate.find(query, Recommend.class);
        // 总页数
        long total = mongoTemplate.count(query, Recommend.class);
        return new PageBean(page.getPageNum(), page.getPageSize(), total, list);
    }
}
